package com.yike.product.interceptor;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.yike.common.api.BarcodeApiResult;
import com.yike.common.tool.ZosClientUtil;
import com.yike.product.vo.GoodsBarcodeApiVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;

/**
 * @author admin
 */

@Slf4j
@Component
public class GoodsBarcodeInterceptor implements Interceptor {

    @Value("${appCode}")
    private String appCode;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        request.addHeader("Authorization", "APPCODE " + appCode);
        return true;
    }


    @Override
    public void onError(ForestRuntimeException e, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.error("onError url:{},------params:{},----------result:{}", forestRequest.getUrl(), JSONObject.toJSONString(forestRequest.getArguments()), forestResponse.getContent());
    }

    @SneakyThrows
    @Override
    public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        log.info("url:【{}】,params:【{}】,result:【{}】", request.getUrl(), JSONObject.toJSONString(request.getArguments()), response.getContent());
        if (response.getStatusCode() != 200) {
            return;
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            GoodsBarcodeApiVo goodsBarcodeApiVo = ((BarcodeApiResult<GoodsBarcodeApiVo>) data).getResult();
            if (StrUtil.isEmpty(goodsBarcodeApiVo.getImg())) {
                return;
            }
            URL url = new URL(goodsBarcodeApiVo.getImg());
            BufferedImage bufferedImage = ImgUtil.read(url);
            String img = goodsBarcodeApiVo.getImg().replace("http://barcodeimg.fegine.com/", "");
            ImageIO.write(bufferedImage, img.split("\\.")[1], out);
            out.toByteArray();
            ZosClientUtil.uploadFile(img, out.toByteArray());
            goodsBarcodeApiVo.setImg(goodsBarcodeApiVo.getImg().replace("http://barcodeimg.fegine.com/", "https://qyzj.obs.cn-sh1.ctyun.cn/"));
        } catch (RuntimeException | IOException e) {
            log.error("图片转换异常,message:{}", e.getMessage(), e);
        }
    }

}
